package com.topchain.entity.cert;


import com.topchain.utils.CertUtil;
import lombok.extern.slf4j.Slf4j;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
@Slf4j
public class GenCert implements ICert {

    @Override
    public X509Certificate genGmCaRootCert(KeyPair keyPair, String dn, int validData, String dnsName, String rfc822Name) throws Exception {
        log.info("=============生成国密CA根证书=============");
        X509Certificate cert = CertUtil.genGmCertHelper(keyPair.getPublic(), keyPair.getPrivate(), dn, validData, dnsName, rfc822Name);
        return cert;
    }

    @Override
    public X509Certificate genStandardCaRootCert(boolean isCA, KeyPair keyPair, String signAlgorithm, String dn, int validData, String dnsName, String rfc822Name) throws Exception {
        log.info("=============生成非国密证书=============");
        X509Certificate cert = CertUtil.genStandardCertHelper(isCA, signAlgorithm, keyPair.getPublic(), keyPair.getPrivate(), dn, validData, dnsName, rfc822Name);
        return cert;
    }

    /**
     * 由CA证书签发生成证书
     *
     * @param caRootCert
     * @param caPrivateKey
     * @param signAlgorithm
     * @param dn
     * @param validData
     * @param dnsName
     * @param rfc822Name
     * @return
     * @throws Exception
     */
    public X509Certificate genCertWithCaSign(X509Certificate caRootCert, PrivateKey caPrivateKey, KeyPair keyPair, String signAlgorithm, String dn, int validData, String dnsName, String rfc822Name) throws Exception {
        log.info("===============生成由CA证书签名的证书===============");
        X509Certificate cert = CertUtil.genCertWithCaSign(caRootCert, caPrivateKey, keyPair.getPublic(), signAlgorithm, dn, validData, dnsName, rfc822Name);
        return cert;
    }

    // 由CA证书签发生成证书(可以指定证书的起止时间)
    public X509Certificate genCertWithCaSign_V2(X509Certificate caRootCert, PrivateKey caPrivateKey, KeyPair keyPair, String signAlgorithm, String dn, long notBefore, long notAfter, String dnsName, String rfc822Name) throws Exception {
        log.info("===============生成由CA证书签名的证书===============");
        X509Certificate cert = CertUtil.genCertWithCaSign_V2(caRootCert, caPrivateKey, keyPair.getPublic(), signAlgorithm, dn, notBefore, notAfter, dnsName, rfc822Name);
        return cert;
    }
}
